class Api::V1::BaseController < ApplicationController
  include Pundit
  attr_reader :current_user

  protected

  #渲染错误信息的方法
  def error_render(resource, status)
    render json: resource, status: status, serializer: ActiveModel::Serializer::ErrorSerializer, adapter: :json_api
  end

  #解析传输的jsonapi报文
  def params_parse(document)
    ActiveModelSerializers::Deserialization.jsonapi_parse(document)
  end

  #如果token失效，返回401，包含过期等
  #否则返回用户实例。
  def authenticate_request!
    unless user_id_in_token?
      render head: :unauthorized,  status: 401
      return
    end
    @current_user = User.find(auth_token[:user_id].to_i)
  end

  #分页功能，处理URL参数
  def paginate(resources)
    resources = resources.page(params[:page] || 1)
    if params[:per_page]
      resources = resources.per(params[:per_page])
    end
    return resources
  end

  #分页函数API返回的meta数据
  def paginate_meta(resources)
    {
      current_page: resources.current_page,
      next_page: resources.next_page,
      prev_page: resources.prev_page,
      total_pages: resources.total_pages,
      total_count: resources.total_count
    }
  end

  private
  #从http报头中读取Authorization字段
  def http_token
    @http_token ||= if request.headers['Authorization'].present?
                      request.headers['Authorization'].split(' ').last
                    end
  end

  #从得到的http_token中解析出内容
  def auth_token
    @auth_token ||= JsonWebToken.decode(http_token)
  end

  #返回用户id
  def user_id_in_token?
    http_token && auth_token && auth_token[:user_id].to_i
  end

end
